package com.summer.service;

import com.alibaba.fastjson.JSON;
import com.summer.dao.UserDao;
import com.summer.bean.User;
import com.summer.result.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/welcomeService")
public class WelcomeService extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Result<String> result = doCheckCookie(request, response);
        String jsonResult = JSON.toJSONString(result);

        // 写入响应流
        PrintWriter out = response.getWriter();
        out.print(jsonResult);
        out.flush(); // 强制输出
        out.close(); // 关闭流
    }

    private Result<String> doCheckCookie(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
//        System.out.println("来到欢迎界面");
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            String username = null;
            String password = null;
            for (Cookie cookie : cookies){
                String name = cookie.getName();
                System.out.println("Cookie Name: " + cookie.getName() + " Value: " + cookie.getValue());
                if("username".equals(name)){
                    username = cookie.getValue();
                }else if ("password".equals(name)){
                    password = cookie.getValue();
                }
            }
            if (username != null && password != null){
//                System.out.println("验证用户名和密码是否正确");
                boolean success = false;
                User user = UserDao.selectByUsernameAndPassword(username, password);
                if(user != null){
                    success = true;
                }
                if (success){
//                    System.out.println("获取session");
                    HttpSession session = request.getSession();
                    return Result.success(username);
                }else {
                    return Result.error("用户名或密码错误");
                }
            }else {
                return Result.error("未查询到cookie");
            }
        }else {
            return Result.error("未查询到cookie");
        }
    }
}
